package net.kesumu.yushabu;

import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import net.kesumu.general.android.EasyStorage.EasyStorage;
import net.kesumu.general.android.view.CustomStatusBar;
import net.kesumu.yushabu.utils.JSONUtil;
import net.kesumu.yushabu.utils.WsConfig;
import net.kesumu.yushabuserver.entity.FriendRequest;
import net.kesumu.yushabuserver.entity.User;

import com.codebutler.android_websockets.WebSocketClient;
import com.umeng.message.PushAgent;

import net.kesumu.yushabu.R;












import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FriendNewActivity extends Activity {
    
    private EasyStorage mEasyStorage;
    
    String mMyId;
    String mUserId;
    String mFriendId;
    String mRequestMessage;
    String mState;
    String mUserName;
    
    FriendNewAdapter mFriendNewAdapter;
    
    ArrayList<ImageView> mPhotoViews = new ArrayList<ImageView>();
    
    
    BroadcastReceiver broadcastReciever_image = new BroadcastReceiver() {
        public void onReceive(android.content.Context context, Intent intent) {
            String location = intent.getExtras().getString("location");
            if(location == null || location.length() == 0) {
//                pd.dismiss();
//                Toast.makeText(context, "Failed to download image", Toast.LENGTH_SHORT).show();
                return;
            }

                //Others' photo

           String photoName = location.substring(0, location.indexOf("."));
//          showToast("mMyPhotoName: "+ mMyPhotoName);
           String photoExtention = location.substring(location.indexOf(".")+1);
//          showToast("mMyPhotoExtention: "+ mMyPhotoExtention);
           Bitmap photo = mEasyStorage.getImageBitmap(photoName, photoExtention);
           for(int i=0;i<mPhotoViews.size();i++) {
               String yuyuChatId = mPhotoViews.get(i).getTag().toString();
               if(yuyuChatId!=null && yuyuChatId.equals(photoName)) {
                   mPhotoViews.get(i).setImageBitmap(photo);
               }
           }

//            Toast.makeText(context, "Download success", Toast.LENGTH_SHORT).show();
        };
    };
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_new);
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
        getActionBar().setCustomView(R.layout.actionbar);
        ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.title_activity_friend_new));
      //Custom the status bar
        CustomStatusBar customStatusBar = new CustomStatusBar(this);
        customStatusBar.setStatusBarColor(findViewById(R.id.statusBarBackground), getResources().getColor(R.color.main));

        
        
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new FriendNewFragment()).commit();
        }
        
        mEasyStorage = new EasyStorage(this, getString(R.string.preference_file_key));
        mMyId = mEasyStorage.getString("mMyId");
        
        /*Intent receiveIntent = getIntent();
        mMyId = receiveIntent.getStringExtra("myId");*/
        
        startUpClient();
        
        PushAgent.getInstance(this).onAppStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.friend_new, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
//        if (id == R.id.action_settings) {
//            return true;
//        }
        return super.onOptionsItemSelected(item);
    }
    
    public void getFriendRequests() {
        sendRequest(jsonUtil.getReceiveFriendRequestJSON(mMyId));
    }
    
    public void viewRequestFriend(View clickedView) {
        Intent friendAcitivityIntent = new Intent(FriendNewActivity.this,FriendActivity.class);
        FriendRequest friendRequest = (FriendRequest) clickedView.getTag();
        friendAcitivityIntent.putExtra("userId", friendRequest.getUserId()+"");
        friendAcitivityIntent.putExtra("userPhotoPath", friendRequest.getUserYuYuChatId()+".jpg");
//        friendAcitivityIntent.putExtra("myId", mMyId);
        if(friendRequest.getState() == FriendRequest.FRIENDREQUEST_INITIATED) {
            friendAcitivityIntent.putExtra("type", FriendActivity.TYPE_FRIEND_REQUEST);
        } else if(friendRequest.getState() == FriendRequest.FRIENDREQUEST_ACCEPTED) {
            friendAcitivityIntent.putExtra("type", FriendActivity.TYPE_FRIEND);
        } else if(friendRequest.getState() == FriendRequest.FRIENDREQUEST_REFUSED) {
            friendAcitivityIntent.putExtra("type", FriendActivity.TYPE_OTHERS);
        }
        startActivity(friendAcitivityIntent);
    }
    
    public void acceptFriendRequest(View clickedView) {
        sendRequest(jsonUtil.getAcceptFriendRequestJSON(
                clickedView.getTag().toString(), mMyId));
    }
    
    public void refuseFriendRequest(View clickedView) {
        sendRequest(jsonUtil.getRefuseFriendRequestJSON(
                clickedView.getTag().toString(), mMyId));
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_friend_new,
                    container, false);
            return rootView;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
         
        if(client != null & client.isConnected()){
            client.disconnect();
        }
    }

    /**
     * Connection with the server
     */
    private WebSocketClient client;
    private JSONUtil jsonUtil;
    void startUpClient() {
        if(client != null && client.isConnected()) {
            return;
        }
        jsonUtil = new JSONUtil(getApplicationContext());
        client = new WebSocketClient(URI.create(WsConfig.URL_WEBSOCKET
                + URLEncoder.encode(WsConfig.SESSION_TAG_DEFAULT)), new WebSocketClient.Listener() {
            public void onConnect() {
                getFriendRequests();
            }
            public void onMessage(String message) {
                parseMessage(message);
            }
            public void onMessage(byte[] data) {
                // Message will be in JSON format
                parseMessage(JSONUtil.bytesToHex(data));
            }
            public void onDisconnect(int code, String reason) {
                String message = String.format(Locale.US,
                        "Disconnected! Code: %d Reason: %s", code, reason);
                showToast(message);
            }
            public void onError(Exception error) {
                showToast("Error! : " + error);
            }
        }, null);
        client.connect();
    }

    //remove the null judge for immediately send a message after connection setup
    private void sendRequest(String message) {
        client.send(message);
    }
    
    private void parseMessage(final String msg) {
 
        try {
            JSONObject jObj = new JSONObject(msg);
 
            // JSON node 'flag'
            String flag = jObj.getString("flag");

            if (flag.equalsIgnoreCase(JSONUtil.FLAG_FRIEND_REQUEST_DESTINATION)) {
                String result = jObj.getString("result");
                showToast(result);
                
                if(result != null && result.equalsIgnoreCase("success")) {
                    mUserId = jObj.getString("userId");
                    mFriendId = jObj.getString("friendId");
                    mRequestMessage = jObj.getString("message");
                    mState = jObj.getString("state");
                    mUserName = jObj.getString("userName");
                    String yuyuChatId = jObj.getString("yuyuChatId");
                    
                    final FriendRequest friendRequest = new FriendRequest(Integer.parseInt(mUserId),
                            Integer.parseInt(mFriendId),mRequestMessage,
                            Integer.parseInt(mState),mUserName);
                    friendRequest.setUserYuYuChatId(yuyuChatId);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mFriendNewAdapter.addItem(friendRequest);
                       }
                    });
                }
                
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        findViewById(R.id.waiting).setVisibility(View.GONE);
                   }
                });
                
            }else if (flag.equals(JSONUtil.FLAG_FRIEND_REQUEST_ACCEPT)) {
                String result = jObj.getString("result");
                showToast(result);
                
                if(result != null && result.equalsIgnoreCase("success")) {
                    finish();
                    Intent intent = new Intent(MainActivity.BROADCAST_TYPE_FRIEND_LIST);
                    sendBroadcast(intent);
                }
            }else if(flag.equals(JSONUtil.FLAG_FRIEND_REQUEST_REFUSE)) {
                String result = jObj.getString("result");
                showToast(result);
                if(result != null && result.equalsIgnoreCase("success")) {
                    finish();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    private void showToast(final String message) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), message,
                        Toast.LENGTH_SHORT).show();
            }
        });
 
    }
    
    
    
    private class FriendNewAdapter extends BaseAdapter{
        ArrayList<FriendRequest> friendList = new ArrayList<FriendRequest>();
        
        public void setData(ArrayList<FriendRequest> fl) {
            this.friendList = fl;
            this.notifyDataSetChanged();
        }
        public int getCount() {
            if(friendList == null) {
                return 0;
            }else {
                return friendList.size();
            }
        }
        public Object getItem(int position) {
            if(friendList == null) {
                return null;
            }else{
                FriendRequest friendRequest = friendList.get(position);
                return friendRequest;
            }
        }
        public long getItemId(int position) {
            return position;
        }
        public View getView(int position, View convertView, ViewGroup parent) {
            FriendRequest friendRequest = (FriendRequest)getItem(position);
            ViewGroup listView = null;
            //Inflate a new view whatever
            listView = (ViewGroup)getLayoutInflater().inflate(R.layout.element_friend_new, null);
            
            TextView mFriendNameView = (TextView)listView.findViewById(R.id.text_name_friendRequest);
            mFriendNameView.setText(friendRequest.getUserName());
            TextView mFriendIdView = (TextView)listView.findViewById(R.id.text_id_friendRequest);
            mFriendIdView.setText(friendRequest.getUserId()+"");
            
            String friendYuYuChatId = friendRequest.getUserYuYuChatId();
            //Remember this image view, then set downloaded image to it
            ImageView mFriendPhotoView = (ImageView) listView.findViewById(R.id.image_photo_friendRequest);
            //Test whether this user's photo is stored on device, if not then download it
            String photoName = friendYuYuChatId;
            String photoExtention = "jpg";
            Bitmap photo = mEasyStorage.getImageBitmap(photoName, photoExtention);

            if(photo!=null) {
                //This photo is already saved
                mFriendPhotoView.setImageBitmap(photo);
            }else {
                //Not saved, go to download
                mFriendPhotoView.setTag(friendYuYuChatId);
                mPhotoViews.add(mFriendPhotoView);
                //Start intent service to download image
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction(ImageIntentService.DOWNLOAD_IMAGE);
                FriendNewActivity.this.registerReceiver(broadcastReciever_image, intentFilter);
                Intent i = new Intent(FriendNewActivity.this, ImageIntentService.class);
                i.putExtra("url", 
                        WsConfig.DOWNLOADIMG_HTTP
                        + friendYuYuChatId + ".jpg");
                i.putExtra("yuyuChatId", friendYuYuChatId);
                FriendNewActivity.this.startService(i);
            }
            
            TextView mRequestMessageView = (TextView)listView.findViewById(R.id.text_message_friendRequest);
            mRequestMessageView.setText(friendRequest.getMessage());
            TextView mRequestStateView = (TextView)listView.findViewById(R.id.text_state_friendRequest);
            mRequestStateView.setText(friendRequest.getState()+"");
            //store the userId onto the buttons
            listView.findViewById(R.id.image_photo_friendRequest).setTag(friendRequest);
            listView.findViewById(R.id.btn_accept).setTag(friendRequest.getUserId());
            listView.findViewById(R.id.btn_refuse).setTag(friendRequest.getUserId());
            if(friendRequest.getState() != FriendRequest.FRIENDREQUEST_INITIATED) {
                listView.findViewById(R.id.btn_friendRequest_acceptAndRefuse).setVisibility(View.GONE);
                listView.findViewById(R.id.btn_friendRequest_completed).setVisibility(View.VISIBLE);
            }
            if(friendRequest.getState() == FriendRequest.FRIENDREQUEST_ACCEPTED) {
                ((TextView)listView.findViewById(R.id.btn_friendRequest_completed_type)).setText(
                        getResources().getString(R.string.btn_accepted));
            }else if(friendRequest.getState() == FriendRequest.FRIENDREQUEST_REFUSED) {
                ((TextView)listView.findViewById(R.id.btn_friendRequest_completed_type)).setText(
                        getResources().getString(R.string.btn_refused));
            }
            /*String location = pixivPicture.location;
            if(location == null || location.length() == 0) {
              Toast.makeText(MainMenuActivity.this, "location error", Toast.LENGTH_SHORT).show();
              return null;
            }
            File imageFile = new File(location);
            if(!imageFile.exists()) {
                Toast.makeText(MainMenuActivity.this, "location file not found", Toast.LENGTH_SHORT).show();
                return null;
            }
            Bitmap bm = BitmapFactory.decodeFile(location);
            ImageView iv = (ImageView)listView.findViewById(R.id.picture_square);
            iv.setImageBitmap(bm);*/
            
            return listView;
        }
        
        public void addItem(final FriendRequest item) {
            this.friendList.add(item);
            this.notifyDataSetChanged();
        }
    }
    
    @SuppressLint("ValidFragment")
    private class FriendNewFragment extends ListFragment {   
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View fragment = inflater.inflate(R.layout.fragment_friend_new, container, false);
            mFriendNewAdapter = new FriendNewAdapter();
            setListAdapter(mFriendNewAdapter);
            return fragment;
        }
        
        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);
            
        }
    }
}
